package HTTP

import (
	"SQL/FSDB"
	"net/http"
)

type addMemberInfo struct {
	MemberID   string
	Nickname   string
	MemberIcon string
}

func addGroupMember(w http.ResponseWriter, req *http.Request) {

	var resCode = Success
	var msg = ""
	var res interface{}
	defer func() {
		writeResult(w, resCode, msg, res)
	}()

	groupID := req.FormValue("groupID")
	pageIndex := req.FormValue("pageIndex")
	pageSize := req.FormValue("pageSize")

	ok := false
	if ok, resCode, msg = isArgsEmpty(groupID, pageIndex, pageSize); ok {
		return
	}
	if ok, resCode, msg = isValidID(groupID, "GroupID"); !ok {
		if resCode == errInvalidID {
			msg = mInvalidGroupID
		}
		return
	}
	pSize := 0
	if ok, pSize, resCode, msg = isValidPageSize(pageSize); !ok {
		return
	}
	pIndex := 0
	if ok, pIndex, resCode, msg = isValidPageIndex(pageIndex); !ok {
		return
	}

	errCode, errMsg, memberList := addableMemberListFromDB(groupID, pIndex, pSize)
	msg = errMsg
	if errCode != Success {
		resCode = errCode
		return
	}
	res = memberList
}

func addableMemberListFromDB(groupID string, pageIndex int, pageSize int) (errCode int, errMsg string, memberList interface{}) {

	friendListSQL := `SELECT u.id,o.nickname,o.icon
						FROM users u,objects o 
						WHERE o.id=u.id 
							AND NOT EXISTS(
    							SELECT m.userid
    							FROM members m 
    							WHERE m.groupid = $1 AND u.id=m.userid
							)
						LIMIT $2 OFFSET $3;`

	rows, err := FSDB.Query(friendListSQL, groupID, pageSize, pageSize*pageIndex)
	defer rows.Close()
	if err != nil {
		return errDBExecFailed, err.Error(), nil
	}
	infoRows := make([]addMemberInfo, 0)
	for rows.Next() {
		var (
			id       string
			nickname string
			icon     string
		)
		err := rows.Scan(&id, &nickname, &icon)
		if err != nil {
			return errDBExecFailed, err.Error(), nil
		}
		info := addMemberInfo{id, nickname, icon}
		infoRows = append(infoRows, info)
	}
	return Success, "获取群组可添加用户列表成功！", infoRows
}
